package com.zhijs.struts.action;

import static java.lang.System.out;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.map.MultiValueMap;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.SessionAware;

import com.h819.core.commons.MyCollectionUtils;
import com.h819.core.db.MyDbUtils;
import com.h819.core.web.jqgrid.JqgridEditBaseAction;

/**
 * @Title: EditAction.java
 * @Description: TODO(参考 com.h819.examples.web.jqgrid.JqgridEditAction)
 * @author H819
 * @date 2010-3-31
 * @version V1.0
 */
public class EditAction extends JqgridEditBaseAction implements SessionAware {

	private Logger log = Logger.getLogger(EditAction.class);
	private QueryRunner runner = new QueryRunner();
	private Connection conn = MyDbUtils.getInstance("h819.properties").getOracleConnection235();
	private Map session;

	// 其他参数处理和一般的 struts2 的 action 没什么两样了

	// 下面的参数，由 struts2 请求自动赋值
	private String ST_STANDARDCODE;
	private String ZHIJS_TYPENAME;
	private String ZHIJS_LANGUAGE_NAME;
	private String ZHIJS_DEPARTMENT;
	private String ST_REMARK;

	// 标准名称是查询平台库得到的，不允许修改
	// private String ST_STANDARD_NAME;

	public String execute() throws Exception {
		String oper = this.getOper();
		log.info(" jqgrid 传过来的 oper 参数是：" + oper);
		// 根据传递过来的不同的编辑标志，执行相应的方法
		if (oper.equals("edit"))
			edit();

		if (oper.equals("add"))
			add();

		if (oper.equals("del"))
			del();

		return null;
	}

	private void edit() {

		log.info("jqgrid, execute edit method.");
		log.info("id :" + this.getId());
		log.info("ST_STANDARD_CODE :" + this.getST_STANDARDCODE());
		log.info("ZHIJS_DEPARTMENT :" + this.getZHIJS_DEPARTMENT());
		log.info("ZHIJS_LANGUAGE_NAME :" + this.getZHIJS_LANGUAGE_NAME());
		log.info("ZHIJS_TYPENAME :" + this.getZHIJS_TYPENAME());
		log.info("ST_REMARK :" + this.getST_REMARK());

		String updateSql = "update zhijs_standard set "
				+ "st_standardcode ='"
				+ this.getST_STANDARDCODE()
				+ "',st_type='"
				+ this.getZHIJS_TYPENAME()
				+ "',st_language_code='"
				+ this.getZHIJS_LANGUAGE_NAME()
				+ "',st_department='"
				+ this.getZHIJS_DEPARTMENT()
				+ "',st_remark='"
				+ this.getST_REMARK()
				+ "',st_lastupdate=sysdate,st_user='zhijs' where st_standardcode='"
				+ this.getStandardCode(this.getId()) + "' and st_department='"
				+ this.getZHIJS_DEPARTMENT() + "'";;

		log.info("updateSql :" + updateSql);

		try {
			runner.update(conn, updateSql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			DbUtils.closeQuietly(conn);
		}
	}

	private void add() {
		log.info("jqgrid, execute add method.");
		log.info("id :" + this.getId());
		log.info("ST_STANDARDCODE :" + this.getST_STANDARDCODE());
		log.info("ZHIJS_DEPARTMENT :" + this.getZHIJS_DEPARTMENT());
		log.info("ZHIJS_LANGUAGE_NAME :" + this.getZHIJS_LANGUAGE_NAME());
		log.info("ZHIJS_TYPENAME :" + this.getZHIJS_TYPENAME());
		log.info("ZHIJS_ZHIJS_REMARK :" + this.getST_REMARK());

		// 如果标准已经存在，则不添加
		// 根据"标准号，部门id"查询

		String searchSql = "select count(1) from zhijs_standard where st_standardcode ='"
				+ this.getST_STANDARDCODE()
				+ "' and st_department='"
				+ this.getZHIJS_DEPARTMENT() + "'";

		String insertSql = "insert into zhijs_standard (id,st_standardcode,st_type,st_language_code,st_department,st_remark,st_lastupdate,st_user) values ("
				+ "zhijs_seq.nextval,'"
				+ this.getST_STANDARDCODE()
				+ "','"
				+ this.getZHIJS_TYPENAME()
				+ "','"
				+ this.getZHIJS_LANGUAGE_NAME()
				+ "','"
				+ this.getZHIJS_DEPARTMENT()
				+ "','"
				+ this.getST_REMARK() + "',sysdate,'zhijs')";

		log.info("searchSql :" + searchSql);
		log.info("insertSql :" + insertSql);

		Map<String, Object> searchResult;
		try {
			searchResult = runner.query(conn, searchSql, new MapHandler());
			
			log.info("searchResult :"+searchResult);
			log.info("count(1) :"+searchResult.get("count(1)"));
			

			if (searchResult!=null&&!searchResult.get("count(1)").toString().equals("0"))// 跳过
			{
				log.info("excute searchSql,add has exsits .");
				for (Iterator it = searchResult.entrySet().iterator(); it
						.hasNext();) {
					Map.Entry entry = (Map.Entry) it.next();
					System.out.println(entry.getKey() + " = "
							+ entry.getValue());
				}
			}

			else // 更新
			{
				log.info("excute insertSql .");
				runner.update(conn, insertSql);
			}

		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} finally {
			DbUtils.closeQuietly(conn);
		}

	}

	private void del() {
		log.info("jqgrid, execute del method." + " jqgrid 传过来的 id 参数是："
				+ this.getId());

		String delSql = "delete from zhijs_standard where st_standardcode = '"
				+ this.getStandardCode(this.getId()) + "'"
				+ " and st_department='" + this.getDepartMentCode(this.getId()) + "'";

		log.info("delSql: " + delSql);

		 try {
		 runner.update(conn, delSql);
		 } catch (SQLException e) {
		 // TODO Auto-generated catch block
		 log.info(this.getST_REMARK() + " : exists");
		 e.printStackTrace();
		 } finally {
		 DbUtils.closeQuietly(conn);
		 }

	}

	/**
	 * 根据 id 得到标准号
	 * @param id
	 * @return
	 */
	private String getStandardCode(String id) {

		// 得到页面显示信息 ，是在 ShowListByDepartmentAction 类中加入 session 的
		List<MultiValueMap> newSearchData = (ArrayList<MultiValueMap>) session
				.get("resultdata");


		String standardCode = "";

		// 查找 标准号
		for (MultiValueMap mvm : newSearchData) {
			log.info(mvm);
			if (mvm.containsValue("id", this.getId())) {
				standardCode = (String) MyCollectionUtils.getSingleValue(mvm
						.getCollection("ST_STANDARDCODE"));
				break;
			}
		}

		// if (newSearchData != null)
		// log.info("newSearchData size :" + newSearchData.size());
		// else
		// log.info("newSearchData is null");
		// log.info("id :" + id);

		return standardCode;
	}

	/**
	 * 根据 id 查询部门id
	 * @param id
	 * @return
	 */
	private String getDepartMentCode(String id) {

		// 得到页面显示信息 ，是在 ShowListByDepartmentAction 类中加入 session 的
		List<MultiValueMap> newSearchData = (ArrayList<MultiValueMap>) session
				.get("resultdata");


		String departMentCode = "";

		// 查找 标准号
		for (MultiValueMap mvm : newSearchData) {
			out.println(mvm);
			if (mvm.containsValue("NUM", this.getId())) {
				departMentCode = (String) MyCollectionUtils.getSingleValue(mvm
						.getCollection("ZHIJS_DEPARTMENTCODE"));
				break;
			}
		}

		// if (newSearchData != null)
		// log.info("newSearchData size :" + newSearchData.size());
		// else
		// log.info("newSearchData is null");
		// log.info("id :" + id);

		return departMentCode;
	}
	
	public void setSession(Map session) {
		this.session = session;
	}

	public String getZHIJS_TYPENAME() {
		return ZHIJS_TYPENAME;
	}

	public void setZHIJS_TYPENAME(String zHIJSTYPENAME) {
		ZHIJS_TYPENAME = zHIJSTYPENAME;
	}

	public String getZHIJS_LANGUAGE_NAME() {
		return ZHIJS_LANGUAGE_NAME;
	}

	public void setZHIJS_LANGUAGE_NAME(String zHIJSLANGUAGENAME) {
		ZHIJS_LANGUAGE_NAME = zHIJSLANGUAGENAME;
	}

	public String getZHIJS_DEPARTMENT() {
		return ZHIJS_DEPARTMENT;
	}

	public void setZHIJS_DEPARTMENT(String zHIJSDEPARTMENT) {
		ZHIJS_DEPARTMENT = zHIJSDEPARTMENT;
	}


	public String getST_STANDARDCODE() {
		return ST_STANDARDCODE;
	}

	public void setST_STANDARDCODE(String sTSTANDARDCODE) {
		ST_STANDARDCODE = sTSTANDARDCODE;
	}

	public String getST_REMARK() {
		return ST_REMARK;
	}

	public void setST_REMARK(String sTREMARK) {
		ST_REMARK = sTREMARK;
	}

}
